package com.csyf.manager.controller.system;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.csyf.manager.entity.SysTrade;
import com.csyf.manager.service.OrderService;
import com.csyf.manager.utils.HttpHelper;
import com.csyf.manager.utils.NumberHelpler;
import com.csyf.manager.utils.ReturnData;
import com.csyf.manager.utils.SignUtils;
import com.csyf.manager.utils.page.JqGridVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author: casper
 * @Description: 订单管理
 * @Date: Created in 2018/11/29 9:11
 */
@Slf4j
@Controller
@RequestMapping("/order")
public class SysOrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 订单列表
     * @param vo
     * @param page
     * @param rows
     * @return
     */
    @PostMapping(value = "list")
    @ResponseBody
    public JqGridVo list(SysTrade vo, Integer page, Integer rows) {
        return orderService.queryOrderByUserId(vo, page, rows);
    }

    /**
     * 订单回调补发
     * @param outTradeNo
     */
    @ResponseBody
    @RequestMapping(value = "retryNotify")
    public ReturnData retryNotify(String outTradeNo) {
        ReturnData returnData = new ReturnData();

        SysTrade sysTrade = orderService.queryOrderByOrderNo(outTradeNo);
        if (null != sysTrade) {
            Map<String, String> hashMap = new TreeMap();
            hashMap.put("out_trade_no", sysTrade.getOutTradeNo());
            hashMap.put("mch_id", sysTrade.getMchId());
            hashMap.put("service", sysTrade.getServiceType());
            hashMap.put("tradeStatus", sysTrade.getTradeStatus());
            hashMap.put("total_fee", NumberHelpler.money2cent(sysTrade.getTotalFee()).toString());
            String agentSignKey = getAgentSignKey(sysTrade.getMchId());
            String sign = SignUtils.map2signkey(hashMap, agentSignKey);
            hashMap.put("sign", sign);
            log.info("[{}] [{}] ,订单回调补发请求参数:{}", outTradeNo, sysTrade.getNotifyUrl(), hashMap);
            String s = HttpHelper.doPostForm(sysTrade.getNotifyUrl(), hashMap);
            log.info("[{}] [{}] ,订单回调补发接受参数:{}", outTradeNo, sysTrade.getNotifyUrl(), s);

            returnData.setCode(0);
            returnData.setMsg("补发成功，下游返回"+ s);
            return returnData;
        } else {
            returnData.setCode(99);
            returnData.setMsg("补发失败，订单号查询失败");
            return returnData;
        }
    }

    @ResponseBody
    @RequestMapping(value = "exportExcle")
    public void exportExcle(SysTrade vo, HttpServletResponse response) throws Exception {

        JqGridVo jqGridVo = orderService.queryOrderByUserId(vo, 1, 100000);
        List<?> rows1 = jqGridVo.getRows();

        ExportParams exportParams = new ExportParams("订单列表", "订单列表 ", ExcelType.XSSF);

        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, SysTrade.class, rows1);

        ServletOutputStream outputStream = response.getOutputStream();

        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename="
                + URLEncoder.encode("boss_" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".xlsx", "UTF-8"));

        sheets.write(outputStream);
        outputStream.close();

        sheets.close();

    }



    public String getAgentSignKey(String mch_id) {
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        String s = stringStringValueOperations.get("signkey:" + mch_id);
        return s;
    }

}
